import React, { PureComponent } from 'react'
import PropTypes from 'prop-types'
import {connect, history} from 'umi'
import { stringify } from 'qs'
import { t } from "@lingui/macro"
import { Page } from 'components'
import List from './components/List'
import CodeTableModal from "./components/Modal";
import Filter from "./components/Filter"
import {Modal, notification, message} from "antd";
import SqlModal from "./components/SqlModal";
import ShowCodeModal from "./components/ShowCodeModal";
import JSZip from 'jszip'
import saveAs from 'file-saver'
import ShowLoadTableModal from "./components/ShowLoadTableModal";
import BasePathTreeModal from "./components/BasePathTreeModal";


@connect(({ code_table, loading }) => ({ code_table, loading }))
class CodeTable extends PureComponent {
  handleRefresh = newQuery => {
    const { location } = this.props
    const { query, pathname } = location
    if(newQuery && newQuery.createTime) {
      newQuery.startDate = newQuery.createTime[0]
      newQuery.endDate = newQuery.createTime[1]
      delete newQuery.createTime
    }
    history.push({
      pathname,
      search: stringify(
        {
          ...query,
          ...newQuery,
        },
        { arrayFormat: 'repeat' }
      ),
    })
  }

  //跳转到字段编辑
  handleGotoColumnList = newQuery => {
    history.push({
      pathname: "/code_table_column",
      search: stringify(newQuery || {}),
    })
  }

  handleTabClick = key => {
    const { pathname } = this.props.location

    history.push({
      pathname,
      search: stringify({
        status: key,
      }),
    })
  }

  get listProps() {
    const { code_table, loading, location, dispatch } = this.props
    const { list, pagination } = code_table
    const { query, pathname } = location
    return {
      options: code_table.options,
      trees: code_table.trees,
      pagination,
      dataSource: list,
      loading: loading.effects['code_table/query'],
      handleGotoColumnList: this.handleGotoColumnList,
      onChange(page) {
        history.push({
          pathname,
          search: stringify({
            ...query,
            page: page.current,
            pageSize: page.pageSize,
          }),
        })
      },
      onDeleteItem: id => {
        dispatch({
          type: 'code_table/delete',
          payload: id,
        }).then(() => {
          this.handleRefresh({
            page:
              list.length === 1 && pagination.current > 1
                ? pagination.current - 1
                : pagination.current,
          })
        })
      },
      onEditItem(item) {
        dispatch({
          type: 'code_table/showModal',
          payload: {
            modalType: 'update',
            currentItem: item,
          },
        })
      },
      //显示sql
      onShowSql(id) {
        dispatch({
          type: 'code_table/querySql',
          payload: {
            id: id,
          },
        })
      },
      //显示代码框
      onShowCode(item) {
        dispatch({
          type: 'code_table/showCode',
          payload: {
            currentItem: item,
          }
        })
      },

      onChildItem(item) {
        dispatch({
          type: 'example_category/showModal',
          payload: {
            modalType: 'create',
            currentItem: {...item},
          },
        })
      },    }
  }

  get modalProps() {
    const { dispatch, code_table, loading } = this.props
    const { currentItem, modalVisible, modalType,resourceTree,resourceIds } = code_table

    return {
      options: code_table.options,
      trees: code_table.trees,
      item: modalType === 'create' ? {...currentItem} : currentItem,
      open: modalVisible,
      destroyOnClose: true,
      maskClosable: false,
      confirmLoading: loading.effects[`code_table/${modalType}`],
      resourceTree: resourceTree,
      resourceIds: resourceIds,
      title: `${
         modalType === 'create' ? t`Create` : t`Update`
      }`,
      centered: true,
      onOk: data => {
        dispatch({
          type: `code_table/${modalType}`,
          payload: data,
        }).then(() => {
          this.handleRefresh()
        })
      },
      onCancel() {
        dispatch({
          type: 'code_table/hideModal',
        })
      },

    }
  }

  get filterProps() {
    const { location, dispatch, code_table} = this.props
    const {query,pathname} = location
    return {
      options: code_table.options,
      trees: code_table.trees,
      filter: {
        ...query,
      },
      onFilterChange(values) {
        history.push({
          pathname,
          search: stringify(values),
        })
      },
      onAdd() {
        dispatch({
          type: 'code_table/showModal',
          payload: {
            modalType: 'create',
          },
        })
      },
      //显示导入框
      onLoadTables() {
        // alert("is rungin")
        dispatch({
          type: 'code_table/updateState',
          payload: {
            showLoadTable: true,
          },
        }).then(() => {
          this.handleRefresh()
        })
      },
    }
  }

  get showSqlProps() {
    const { location, dispatch, code_table} = this.props

    return {
      showSql: code_table.showSql,
      onCancel() {
        dispatch({
          type: "code_table/hideSqlModal"
        })
      },
      onExec(drop) {
        //执行创建语句
        dispatch({
          type: 'code_table/queryExec',
          payload: {id: code_table.showSql.tableId, drop: drop},
        }).then((res)=>{
          // const [messageApi] = message.useMessage();
          message.info(res.res, 30);
        })
      },
    }
  }

  get showCodeProps() {
    const {location, dispatch, code_table, options} = this.props

    return {
      code_table,
      queryCodeFile(payload) {
        dispatch({
          type: "code_table/queryCodeFile",
          payload: payload
        })
      },
      queryTemplate(payload) {
        dispatch({
          type: "code_table/queryCodeTableTemplateByGroupId",
          payload: payload
        }).then((templateMap)=>{
          let keys = Object.keys(templateMap)
          if(keys.length>0) {
            //请求同步默认代码信息
            dispatch({
              type: "code_table/queryCodeFile",
              payload: {
                id: code_table.currentItem.id,
                templateId: keys[0],
                path: code_table.selectBasePath,
                codeNamespace: code_table.codeNamespace
              }
            })

          }
        })

        //请求分组目录信息
        dispatch({
          type: "code_table/queryBaseDirTree",
          payload: {groupId: payload.groupId}
        })
      },
      onSaveCode(payload) {
        dispatch({
          type: "code_table/querySaveCode",
          payload: payload
        }).then(function (res) {
          if(res.code === 5000) {
            notification.error({message: "保存失败， 请检查脚本"})
          } else {
            notification.success({message: "保存成功"})
          }
        })
      },
      //获取代码
      getCodes(payload) {
        dispatch({
          type: "code_table/queryCodes",
          payload: payload
        }).then(function (res) {
          if(res.code === 5000) {
            notification.error({message: "创建失败， 请检查脚本"})
          } else {
            notification.success({message: "代码包创建成功"})
            //打包下载
            var zip = new JSZip();
            for(var file in res.payload) {
              zip.file(file, res.payload[file])
            }
            zip.generateAsync({type: "blob"})
              .then(function (content) {
                saveAs(content, "code.zip")
              })
          }
        })
      },
      //变更命名空间
      onChangeCodeNamespace(namespace) {
        dispatch({
          type: "code_table/updateState",
          payload: {codeNamespace: namespace}
        })
      },
      //显示目录选择框
      showSelectDir() {
        dispatch({
          type: "code_table/updateState",
          payload: {showBasePath: true}
        })
      },
      options: code_table.options,
      showCode: code_table.showCode,
      onCancel() {
        dispatch({
          type: "code_table/hideCode",
        })
      }
    }
  }

  //获取数据导入框属性
  get showLoadTablesProps() {
    const { location, dispatch, code_table} = this.props
    return ({
      dbTables: code_table.options.dbTables,
      onSaveTables: (tables) => {
        // alert("正在保存表");
        dispatch({
          type: 'code_table/querySaveTables',
          payload: {tableNames: tables}
        }).then((res) => {
          if(res.code === 2000) {
            notification.success({message: "同步成功"})
          } else {
            notification.error({message: res.msg})
          }
        })
      },
      onCancel: () => {
        dispatch({
          type: 'code_table/updateState',
          payload: {
            showLoadTable: false,
          },
        })
      },
    })
  }

  //目录选择框属性
  get showSelectDirProps() {
    const {location, dispatch, code_table, options} = this.props
    return ({
      onCancel: () => {
        dispatch({
          type: "code_table/updateState",
          payload: {showBasePath: false}
        })
      },
      onOk: (res) => {
        dispatch({
          type: "code_table/updateState",
          payload: {showBasePath: false, selectBasePath: res}
        })
      }
    })
  }

  render() {
    const {code_table} = this.props;
    return (
      <Page inner>

        <Filter {...this.filterProps} />
        <List {...this.listProps} />
        <CodeTableModal {...this.modalProps} />
        <SqlModal {...this.showSqlProps} />
        <ShowCodeModal {...this.showCodeProps} />
        <ShowLoadTableModal open={code_table.showLoadTable} {...this.showLoadTablesProps} />
        <BasePathTreeModal code_table={code_table} showBasePath={code_table.showBasePath} {...this.showSelectDirProps} />
      </Page>
    )
  }
}

CodeTable.propTypes = {
  code_table: PropTypes.object,
  loading: PropTypes.object,
  location: PropTypes.object,
  dispatch: PropTypes.func,
}

export default CodeTable

